#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

// 打印正确的程序使用方法
void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " <ip> <port>" << std::endl;
}

// ./tcp_client 192.168.1.100 8080
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverIp = argv[1];
    uint16_t serverPort = atoi(argv[2]);
    
    bool connectAlive = false; // 是否已经建立了连接
    int sock = 0;
    while(true)
    {
        if(!connectAlive)
        {
            sock = socket(AF_INET, SOCK_STREAM, 0);
            if(sock < 0) { // 创建套接字失败
                std::cerr << "socket error" << std::endl;
                exit(2);
            }

            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_port = htons(serverPort);
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(serverIp.c_str());

            if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
            { // 连接失败
                std::cerr << "connect error: " << errno << " " << strerror(errno) << std::endl;
                exit(3);
            }
            // 建立连接成功，讲connectALive 设为true
            std::cout << "connect success." << std::endl;
            connectAlive = true;
        }

        std::cout << "请输入# " << std::endl;
        std::string line;
        std::getline(std::cin, line);
        if(line == "quit") break;

        ssize_t s = send(sock, line.c_str(), line.size(), 0);
        if(s > 0) 
        { // send 成功
            char buffer[1024];
            ssize_t r = recv(sock, buffer, sizeof(buffer), 0);
            if(r > 0) { // recv 成功
                buffer[r] = '\0';
                std::cout << "server response: " << buffer << std::endl;
            } else { // recv 失败
                std::cerr << "recv() error: client receiving message failed." << std::endl;
                close(sock);
                connectAlive = false;
            }
        } 
        else {
            std::cerr << "send() error: client sending message failed." << std::endl;
            close(sock);
        }
    }

    return 0;
}